// src/store/slices/notificationSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import notificationService from '../../services/notificationService';
import api from '../../services/api';

interface Notification {
  id: string;
  type: 'chat' | 'translation' | 'voice' | 'subscription' | 'system';
  title: string;
  message: string;
  data?: any;
  read: boolean;
  timestamp: Date;
}

interface NotificationState {
  notifications: Notification[];
  unreadCount: number;
  hasPermission: boolean;
  token: string | null;
  isLoading: boolean;
  error: string | null;
}

const initialState: NotificationState = {
  notifications: [],
  unreadCount: 0,
  hasPermission: false,
  token: null,
  isLoading: false,
  error: null,
};

// 异步actions
export const requestPermission = createAsyncThunk(
  'notification/requestPermission',
  async () => {
    const hasPermission = await notificationService.requestPermissions();
    return hasPermission;
  }
);

export const loadNotifications = createAsyncThunk(
  'notification/loadNotifications',
  async ({ page = 1 }: { page?: number } = {}) => {
    const response = await api.get('/api/notifications', {
      params: { page, size: 20 },
    });
    return response.data;
  }
);

export const markAsRead = createAsyncThunk(
  'notification/markAsRead',
  async (notificationId: string) => {
    await api.put(`/api/notifications/${notificationId}/read`);
    return notificationId;
  }
);

export const markAllAsRead = createAsyncThunk(
  'notification/markAllAsRead',
  async () => {
    await api.put('/api/notifications/read-all');
  }
);

export const deleteNotification = createAsyncThunk(
  'notification/deleteNotification',
  async (notificationId: string) => {
    await api.delete(`/api/notifications/${notificationId}`);
    return notificationId;
  }
);

export const clearAllNotifications = createAsyncThunk(
  'notification/clearAll',
  async () => {
    await api.delete('/api/notifications/clear-all');
  }
);

const notificationSlice = createSlice({
  name: 'notification',
  initialState,
  reducers: {
    addNotification: (state, action: PayloadAction<Notification>) => {
      state.notifications.unshift(action.payload);
      if (!action.payload.read) {
        state.unreadCount += 1;
      }

      // 限制通知数量
      if (state.notifications.length > 100) {
        state.notifications = state.notifications.slice(0, 100);
      }
    },

    removeNotification: (state, action: PayloadAction<string>) => {
      const notification = state.notifications.find((n) => n.id === action.payload);
      if (notification && !notification.read) {
        state.unreadCount -= 1;
      }
      state.notifications = state.notifications.filter((n) => n.id !== action.payload);
    },

    updateNotification: (
      state,
      action: PayloadAction<{ id: string; updates: Partial<Notification> }>
    ) => {
      const notification = state.notifications.find((n) => n.id === action.payload.id);
      if (notification) {
        const wasUnread = !notification.read;
        Object.assign(notification, action.payload.updates);

        // 更新未读计数
        if (wasUnread && notification.read) {
          state.unreadCount -= 1;
        } else if (!wasUnread && !notification.read) {
          state.unreadCount += 1;
        }
      }
    },

    setHasPermission: (state, action: PayloadAction<boolean>) => {
      state.hasPermission = action.payload;
    },

    setToken: (state, action: PayloadAction<string>) => {
      state.token = action.payload;
    },

    updateUnreadCount: (state) => {
      state.unreadCount = state.notifications.filter((n) => !n.read).length;
    },

    clearError: (state) => {
      state.error = null;
    },

    resetNotifications: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      // Request Permission
      .addCase(requestPermission.fulfilled, (state, action) => {
        state.hasPermission = action.payload;
      })
      // Load Notifications
      .addCase(loadNotifications.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(loadNotifications.fulfilled, (state, action) => {
        state.isLoading = false;
        state.notifications = action.payload.notifications;
        state.unreadCount = action.payload.unreadCount;
      })
      .addCase(loadNotifications.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.error.message || '加载失败';
      })
      // Mark as Read
      .addCase(markAsRead.fulfilled, (state, action) => {
        const notification = state.notifications.find((n) => n.id === action.payload);
        if (notification && !notification.read) {
          notification.read = true;
          state.unreadCount -= 1;
        }
      })
      // Mark All as Read
      .addCase(markAllAsRead.fulfilled, (state) => {
        state.notifications.forEach((n) => (n.read = true));
        state.unreadCount = 0;
      })
      // Delete Notification
      .addCase(deleteNotification.fulfilled, (state, action) => {
        const notification = state.notifications.find((n) => n.id === action.payload);
        if (notification && !notification.read) {
          state.unreadCount -= 1;
        }
        state.notifications = state.notifications.filter((n) => n.id !== action.payload);
      })
      // Clear All
      .addCase(clearAllNotifications.fulfilled, (state) => {
        state.notifications = [];
        state.unreadCount = 0;
      });
  },
});

export const {
  addNotification,
  removeNotification,
  updateNotification,
  setHasPermission,
  setToken,
  updateUnreadCount,
  clearError,
  resetNotifications,
} = notificationSlice.actions;

export default notificationSlice.reducer;